//package com.heo.server;
//
//import java.io.IOException;
//import java.util.HashMap;
//import java.util.Map;
//import org.apache.log4j.Logger;
//import com.heo.pojo.DeviceInfoEntity;
//import com.heo.pojo.DeviceModelEntity;
//import com.heo.pojo.JsonArgs;
//import com.heo.pojo.OrgInfoEntity;
//import com.heo.pojo.StatusDictEntity;
//import com.heo.pub.ApplicationContextUtil;
//import com.heo.pub.DictEnum;
//import com.heo.service.DeviceInfoService;
//import com.heo.service.DeviceModelService;
//import com.heo.service.OrgInfoService;
//import com.heo.service.StatusDictService;
//import com.heo.thread.SendMessageSocketThread;
//import com.heo.util.CRC16;
//import com.heo.util.DeviceNettyUtils;
//import com.heo.util.GsonUtils;
//import com.heo.util.NettyChannelMapUtils;
//import com.heo.util.TranscodingUtils;
//import com.heo.util.Utils;
//import io.netty.buffer.Unpooled;
//import io.netty.channel.ChannelHandlerContext;
//import io.netty.channel.SimpleChannelInboundHandler;
//
///**
// * Created by zhangcf handler不是一个单例.即每个channel下都会有自己的一个handler实例.
// * 对于使用spring注解时，一定要注解该类为多例。否则通道断开再重新建立时，会提示 NettyServerHandler is not
// * a @Sharable handler, so can't be added or removed multiple times.
// */
////@Component
////@Scope("prototype")
//public class NettyServerTransparentHandle extends SimpleChannelInboundHandler<String> {
//
//	private static Logger logger = Logger.getLogger(NettyServerTransparentHandle.class);
//	public ChannelHandlerContext mCtx;
//	private String deviceImei = null;
//	private String macAddress = null;
//	private String query = "";       //服务器与板子之间的查询
//	private String heartbeat = "";   //板子跟洗衣机板子之间的心跳
//	private String initCmd = "";    //初始化主板指令
//	private String receiveScriptEngine = "";
//	private String sendScriptEngine = "";
//	private String appId = "";
//	private String callUrl = "";
//	private Map<String, StatusDictEntity> statusDictMap;
//	
//	@Override
//	public void channelActive(ChannelHandlerContext ctx) throws Exception {
//		this.mCtx = ctx;
//	}
//
//	@Override
//	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
//		try {
//			String jsonString = msg;
//			Map<String, Object> rspJsonMap = null;
//			logger.info("macAddress = " + macAddress + ", read message = " + jsonString);
//			JsonArgs jsonArgs = (JsonArgs) GsonUtils.jsonToObject(jsonString,
//					JsonArgs.class);
//			if (jsonArgs != null) {
//				Integer option = jsonArgs.getO();
//				if (Utils.checkNull(jsonArgs.getM())) {
//					macAddress = jsonArgs.getM();
//				}
//
//				if (Utils.checkNull(option)) {
//					if (!Utils.checkNull(macAddress)) {
//						close();
//						throw new Exception(macAddress + "设备不存在请联系管理员!!");
//					}
//					rspJsonMap = new HashMap<String, Object>();
//					rspJsonMap.put("o", option);
//					switch (option) {
//					case 1:
//						// 初始化设备，并入库
//					    DeviceInfoService deviceInfoService = (DeviceInfoService) ApplicationContextUtil.getBeanById("deviceInfoService");
//					    DeviceModelService deviceModelService = (DeviceModelService) ApplicationContextUtil.getBeanById("deviceModelService");
//					    StatusDictService statusDictService = (StatusDictService) ApplicationContextUtil.getBeanById("statusDictService");
//					    OrgInfoService orgInfoService  = (OrgInfoService) ApplicationContextUtil.getBeanById("orgInfoService");
//					    DeviceInfoEntity deviceInfo = deviceInfoService.getDeviceInfoMap(macAddress);
//					    if(deviceInfo == null) {
//					    	throw new Exception(macAddress + "设备不存在请联系管理员!!");
//					    }
//					    deviceImei = deviceInfo.getDeviceImei();
//					    DeviceModelEntity deviceModel = deviceModelService.getDeviceModelMap(deviceInfo.getDeviceModelId());
//					    receiveScriptEngine = deviceModel.getReceivePretreatmentCode();
//					    sendScriptEngine = deviceModel.getSendPretreatmentCode();
//					    deviceInfoService.initDeviceInfo(jsonArgs);
//					    OrgInfoEntity orgInfoEntity = orgInfoService.getByKey(deviceInfo.getDeviceImei());
//					    appId = orgInfoEntity.getAppId();
//					    callUrl = orgInfoEntity.getCallUrl();
////					    NettyChannelMapUtils.add(appId, deviceImei, deviceInfo.getDeviceChannelNum(), Utils.getShort(deviceModel.getDeviceModel()), this);
//						DeviceNettyUtils.deviceInitResult(rspJsonMap);
//						sendMessage(rspJsonMap);
//						rspJsonMap.clear();
//						query = "F1F11001006B7C";
//						rspJsonMap.put("h", "F1F12F01005B70");
//						// 需要 轮询功能
//						rspJsonMap.put("a", 100);
//						rspJsonMap.put("o", 3);
//						String message = GsonUtils.objectToJson(rspJsonMap);
//						SendMessageSocketThread sendWaterThared = new SendMessageSocketThread(appId, deviceImei, message, 10000);
//						new Thread(sendWaterThared).start();
//						statusDictMap = statusDictService.getStatusDictMap(deviceModel.getDeviceModelId());
//						heartbeat = DeviceNettyUtils.scriptEngineCmd(sendScriptEngine, "01");
//						query = DeviceNettyUtils.scriptEngineCmd(sendScriptEngine, "02");
//						initCmd = DeviceNettyUtils.scriptEngineCmd(sendScriptEngine, "03");
//						//发送主板跟主板之间的心跳
//						if(Utils.checkNull(initCmd)) {
//							rspJsonMap.clear();
//							int payMode = 2;   //支付模式，1、实时支付，2、预存
//							int waterMode = 2;  //计费模式，1、按次计费，2、按时间计费
//							int optionMode = 2;  //按钮模式，1、按住出水，放手关水， 2、按一下出水，再按一下关水
//							int maxWater  = 5;   //最大防水量
//							double waterCalc = 28;  //1什水多少脉冲
//							int max = (int) (maxWater * waterCalc);
//							String maxStr = TranscodingUtils.hex10To16(max, 4);
//							StringBuilder sBuilder = new StringBuilder("F1F1110A");
//							sBuilder.append("0").append(payMode);
//							sBuilder.append("0").append(waterMode);
//							sBuilder.append("0").append(optionMode);
//							sBuilder.append(maxStr.toUpperCase());
//							sBuilder.append("0000000000");
//							sBuilder.append(CRC16.calcCrc16(sBuilder.toString()));
//							//初始化指令结果 按次计费
//							initCmd = "F1F1110A020102008C0000000000362B";
//							//按时间计费
//							initCmd = sBuilder.toString();
//							
//							rspJsonMap.clear();
//							rspJsonMap.put("h", initCmd);
//							rspJsonMap.put("o", 3);
//							String messages = GsonUtils.objectToJson(rspJsonMap);
////							SendMessageTransparentThread sendMessageTransparentThread = new SendMessageTransparentThread(
////									appId, deviceImei, messages, 5000);
////							NettyChannelMapUtils.sendTaskThreadPool.execute(sendMessageTransparentThread);
//							SendMessageSocketThread sendMessageTransparentThread = new SendMessageSocketThread(appId, deviceImei, messages, 5000);
//							new Thread(sendMessageTransparentThread).start();
//						}
//						break;
//					case 2:
//						if(Utils.checkNull(query)){
//							rspJsonMap.put("h", query);
//						}
//						NettyChannelMapUtils.refreshDeviceControlInfoExpire(appId, deviceImei);// 设备有消息上来，在redis里做延期
//						sendMessage(rspJsonMap);
//						break;
//					case 3:
//						if (!Utils.checkNull(deviceImei)) {
//							throw new Exception("设备不存在请联系管理员!!");
//						}
//						String h = jsonArgs.getH();
//						if(Utils.checkNull(h)) {
//							if(h.startsWith("F3F3")){
//								String cmd = h.substring(4, 6);
//								String sendCode = "";
//								if("2F".equals(cmd)){
//									String hexString = h.substring(12, 14);
//									String errorCode = TranscodingUtils.hexString2binaryString(hexString);
//									NettyChannelMapUtils.errorCallBackSendStatus(appId, deviceImei,DictEnum.CallBackType.STATUS_REPORT, errorCode, callUrl, statusDictMap);
//									sendCode = "F4F42F010097BC";
//									rspJsonMap.put("h", sendCode);
//								}else if("1F".equals(cmd)){
//									String code = h.substring(10, h.length() - 4);
//									NettyChannelMapUtils.callBackSendStatus(appId, deviceImei,DictEnum.CallBackType.STATUS_REPORT, code, callUrl);
//									sendCode = "F4F41F010097B3";
//									rspJsonMap.put("h", sendCode);
//								}
//							}else if(h.startsWith("F2F2")){
//								String cmd = h.substring(4, 6);
//								//10的出水板状态暂时不用管
//								if("10".equals(cmd) || "12".equals(cmd)){
//									if(h.length() > 14){
//										String code = h.substring(10, h.length() - 4);
//										NettyChannelMapUtils.callBackSendStatus(appId, deviceImei,DictEnum.CallBackType.STATUS_REPORT, code, callUrl);
//									}
//								}
//							}
//							NettyChannelMapUtils.refreshDeviceControlInfoExpire(appId, deviceImei);// 设备有消息上来，在redis里做延期
//						}else{
//							rspJsonMap.put("t", 120); // 心跳
//						}
//						sendMessage(rspJsonMap);
//						break;
//					}
//				}
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//			NettyChannelMapUtils.remove(appId, deviceImei);
//			close();
//		}
//	}
//
//	/**
//	 * 发送消息
//	 * 
//	 * @param rspJsonMap
//	 * @throws Exception
//	 */
//	public synchronized void sendMessage(Map<String, Object> rspJsonMap)
//			throws Exception {
//		if (rspJsonMap != null && rspJsonMap.size() > 0 && mCtx != null) {
//			String rspJson = GsonUtils.objectToJson(rspJsonMap);
//			mCtx.writeAndFlush(rspJson + "\n");
//			logger.info("macAddress=" + macAddress + ", send message = "
//					+ rspJson);
//		}
//	}
//	
//	
//	/**
//	 * 发送消息
//	 * 
//	 * @param rspJsonMap
//	 * @throws Exception
//	 */
//	public synchronized void sendMessage(String rspJson) throws Exception {
//		if (Utils.checkNull(rspJson) && mCtx != null) {
//			mCtx.writeAndFlush(rspJson + "\n");
//			logger.info("macAddress=" + macAddress + ", send message = " + rspJson);
//		}
//	}
//
//	public void close() throws IOException {
//		if (mCtx != null) {
//			NettyChannelMapUtils.remove(appId, deviceImei);
//			mCtx.close();
//		}
//	}
//	
//	@Override
//	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//		super.channelReadComplete(ctx);
//		// 刷新挂起的数据到远端
//		ctx.writeAndFlush(Unpooled.EMPTY_BUFFER);
//	}
//	
//	@Override
//	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//		logger.info(cause.getMessage());
//		if (Utils.checkNull(deviceImei)) {
//			NettyChannelMapUtils.remove(appId, deviceImei);
//		}
//		logger.info(macAddress + " exceptionCaught channel close");
//		ctx.close();
//	}
//}
